package com.wangchao.administrator.zenmechi.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;

/**
 * Created by Administrator on 2016/10/18.
 */
public class SearchHistoryDbHelper extends OrmLiteSqliteOpenHelper {

    private static SearchHistoryDbHelper helper;
    private Dao<SearchHistory,Long> searchHistoryDao;

    private static final String DB_NAME="db_history";
    private static final int DB_VERSION=1;

    public SearchHistoryDbHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    public static SearchHistoryDbHelper getInstance(Context context){
        if(helper == null){
            helper=new SearchHistoryDbHelper(context);
        }
        return helper;
    }


    public Dao<SearchHistory,Long> getHistoryDao()  {
        if(searchHistoryDao==null){
            try {
                searchHistoryDao=getDao(SearchHistory.class);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return searchHistoryDao;
    }
    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource,SearchHistory.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource,
                          int oldVersion, int newVersion) {
        if (newVersion>oldVersion){
            try {
                TableUtils.dropTable(connectionSource,SearchHistory.class,true);
                TableUtils.createTable(connectionSource,SearchHistory.class);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
